require 'rubygems'
require 'json'

class GMCP
  def self.notify(text)
    return text if text !~ /\{gmcp\}/
    ret_text = ''
    text.clean_colors.split(/\{gmcp\}/).each {|t|
      next if t !~ /(\w+)\.(\w+) (\{.+\})(.*)/
      base, type, data, ret = $1, $2, $3, $4
      self.interpret(base, type, JSON.parse(data))
      ret_text += $4
    }
    ret_text.empty? ? nil : ret_text
  end
  
  def self.interpret(base, type, data)
    puts "PACKET #{base}.#{type}"
    (self.char(type, data);return) if base == 'char'
    (self.room(type, data);return) if base == 'room'
    (self.quest(data);return) if base == 'comm' && type == 'quest'
    echo "#{base}.#{type} -- #{data}"
  end
  
  def self.char(type, data)
    data.each {|k,v| Char[k] = v}
  end
  
  def self.room(type, data)
    if type == 'info'
      Map.set_room(data['num'], data['name'], data['zone'], data['terrain'], data['details'], data['exits'], data['coord'])
    elsif type == 'area'
      Map.set_area(data['id'], data['texture'], data['x'], data['y'], data['z'], data['flags'], data['name'], data['col'])
    end
  end
  
  def self.quest(data)
    Quest.set_data(data)
  end
end

class Quest
  @@data ||= nil
  
  def self.set_data(data)
    @@data = data
    self.show
  end
  def self.data; @@data end
  
  def self.show
    echo @@data
    return unless @@data.key?('targ')
    area_id = $db.get_first_value("SELECT id FROM Area WHERE name=?", @@data['area'])
    room = $db.get_first_value("SELECT m.room_id FROM Mob m WHERE m.name=? AND m.area_id=?", @@data['targ'], area_id)
    $app.add_boxes['chat'].display_text("Quest to kill * \x1B[32m#{@@data['targ']}\x1B[0m (\x1B[36m#{@@data['room']}\x1B[0m) -- #{@@data['area']} (#{go2_string(room)})\n")
  end
end

#comm.quest -- {'wait' => 14, 'action' => 'status'}
#comm.quest -- {'wait' => 15, 'action' => 'fail'}
#comm.quest -- {'timer' => 60, 'area' => 'Faerie Tales', 'action' => 'start', 'room' => 'A Great Palace', 'targ' => 'the sixth prince'}
#comm.quest -- {'time' => 48, 'action' => 'killed'}
#comm.quest -- {'trains' => 0, 'totqp' => 40, 'daily' => 1, 'double' => 0, 'mccp' => 2, 'completed' => 158, 'tierqp' => 0, 'qp' => 18, 'gold' => 3844, 'pracs' => 0, 'tp' => 0, 'action' => 'comp', 'wait' => 30, 'lucky' => 0}

### GMCP char.base
Char.add_vars('name', 'class', 'subclass', 'race', 'clan', 'pretitle', 'perlevel', 'tier', 'remorts', 'redos')
### GMCP char.vitals
Char.add_resources('hp', 'mana', 'moves')
### GMCP char.stats
Char.add_resources('str', 'int', 'wis', 'dex', 'con', 'luck')
Char.add_vars('hr', 'dr', 'saves')
### GMCP char.status
Char.add_vars('level', 'tnl', 'hunger', 'thirst', 'align', 'state', 'pos', 'enemy', 'enemypct')
### GMCP char.worth
Char.add_vars('gold', 'bank', 'qp', 'tp', 'trains', 'pracs')